<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import type { EtlTaskDTO } from '@/service/api/dataplatform/etl';
import { createEtlTask, updateEtlTask, getEtlTask } from '@/service/api/dataplatform/etl';
import { getDataSourceList } from '@/service/api/dataplatform/datasource';

const emit = defineEmits<{
  success: [];
}>();

const visible = ref(false);
const loading = ref(false);
const operateType = ref<'add' | 'edit'>('add');
const formRef = ref<FormInstance>();

const formData = reactive<EtlTaskDTO>({
  name: '',
  taskType: 'FULL',
  sourceId: 0,
  targetId: 0,
  sourceConfig: '',
  targetConfig: '',
  transformConfig: '',
  scheduleConfig: '',
  status: 1,
  remark: ''
});

const rules: FormRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  sourceId: [{ required: true, message: '请选择源数据源', trigger: 'change' }],
  targetId: [{ required: true, message: '请选择目标数据源', trigger: 'change' }]
};

const title = computed(() => (operateType.value === 'add' ? '新增ETL任务' : '编辑ETL任务'));

const dataSourceList = ref<any[]>([]);

/** 打开抽屉 */
async function open(type: 'add' | 'edit', id?: number) {
  operateType.value = type;
  visible.value = true;

  // 加载数据源列表
  await loadDataSources();

  if (type === 'edit' && id) {
    loading.value = true;
    try {
      const { data } = await getEtlTask(id);
      Object.assign(formData, data);
    } finally {
      loading.value = false;
    }
  } else {
    resetForm();
  }
}

/** 加载数据源列表 */
async function loadDataSources() {
  try {
    const { data } = await getDataSourceList({ pageNum: 1, pageSize: 1000 });
    dataSourceList.value = data.rows;
  } catch (error) {
    console.error('加载数据源失败', error);
  }
}

/** 重置表单 */
function resetForm() {
  formData.name = '';
  formData.taskType = 'FULL';
  formData.sourceId = 0;
  formData.targetId = 0;
  formData.sourceConfig = '';
  formData.targetConfig = '';
  formData.transformConfig = '';
  formData.scheduleConfig = '';
  formData.status = 1;
  formData.remark = '';
  formRef.value?.clearValidate();
}

/** 提交 */
async function handleSubmit() {
  await formRef.value?.validate();

  loading.value = true;
  try {
    if (operateType.value === 'add') {
      await createEtlTask(formData);
      ElMessage.success('创建成功');
    } else {
      await updateEtlTask(formData.id!, formData);
      ElMessage.success('更新成功');
    }
    visible.value = false;
    emit('success');
  } finally {
    loading.value = false;
  }
}

/** 关闭抽屉 */
function handleClose() {
  visible.value = false;
  resetForm();
}

defineExpose({
  open
});
</script>

<template>
  <el-drawer
    v-model="visible"
    :title="title"
    size="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入任务名称" />
      </el-form-item>

      <el-form-item label="任务类型" prop="taskType">
        <el-radio-group v-model="formData.taskType">
          <el-radio value="FULL">全量</el-radio>
          <el-radio value="INCREMENTAL">增量</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="源数据源" prop="sourceId">
        <el-select v-model="formData.sourceId" placeholder="请选择源数据源" class="w-full">
          <el-option
            v-for="item in dataSourceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="目标数据源" prop="targetId">
        <el-select v-model="formData.targetId" placeholder="请选择目标数据源" class="w-full">
          <el-option
            v-for="item in dataSourceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="源配置">
        <el-input
          v-model="formData.sourceConfig"
          type="textarea"
          :rows="4"
          placeholder="请输入源配置JSON"
        />
      </el-form-item>

      <el-form-item label="目标配置">
        <el-input
          v-model="formData.targetConfig"
          type="textarea"
          :rows="4"
          placeholder="请输入目标配置JSON"
        />
      </el-form-item>

      <el-form-item label="转换配置">
        <el-input
          v-model="formData.transformConfig"
          type="textarea"
          :rows="4"
          placeholder="请输入转换配置JSON"
        />
      </el-form-item>

      <el-form-item label="调度配置">
        <el-input
          v-model="formData.scheduleConfig"
          type="textarea"
          :rows="4"
          placeholder="请输入调度配置JSON"
        />
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-drawer>
</template>
